<html>
<head>
<script src="gears_init.js"></script>
<script>
  if (!window.google || !google.gears) {
    location.href = "http://gears.google.com/?action=install&message=Install gears to use this app" +
                    "&return=";
  }
</script>
<script type="text/javascript">

var db = google.gears.factory.create('beta.database');
function init() {
	db.open('database-test');

	db.execute('DROP TABLE IF EXISTS Assignments');
	db.execute('DROP TABLE IF EXISTS Classes');
	db.execute('DROP TABLE IF EXISTS Semester');

	db.execute('CREATE TABLE IF NOT EXISTS Assignments (id INTEGER PRIMARY KEY, class_id INT, name TEXT, complete BOOLEAN, type TEXT, comments TEXT, datum DATE)');
	db.execute('CREATE TABLE IF NOT EXISTS Classes (id INTEGER PRIMARY KEY, name TEXT, semester_id INT, color TEXT)');
	db.execute('CREATE TABLE IF NOT EXISTS Semester (id INTEGER PRIMARY KEY, name TEXT, is_default BOOLEAN)');

	db.execute("INSERT INTO Semester (name, is_default) VALUES ('Winter 2009', 'true')");
	db.execute("INSERT INTO Classes (name, semester_id, color) VALUES ('IT347', 1, 'blue')");
	db.execute("INSERT INTO Classes (name, semester_id, color) VALUES ('CS340', 1, 'red')");

	db.execute("INSERT INTO Assignments(class_id, name, type, datum) VALUES (1, 'Read Ch.1', 'Reading', '2009-01-14')");
	db.execute("INSERT INTO Assignments(class_id, name, type, datum) VALUES (1, 'HW Ch.1', 'Homework', '2009-01-14')");
	db.execute("INSERT INTO Assignments(class_id, name, datum) VALUES (1, 'Read Ch.2', '2009-01-21')");
	db.execute("INSERT INTO Assignments(class_id, name, datum) VALUES (2, 'Read Ch.1', '2009-01-14')");
	db.execute("INSERT INTO Assignments(class_id, name, type, datum) VALUES (2, 'Midterm', 'Exam', '2009-01-15')");
	
	refreshSemester();
}
function getAllSemesters() {
	var semester_rs = db.execute("SELECT id, name FROM Semester");
	semesters = new Array();
	while (semester_rs.isValidRow()) {
		semesters[semester_rs.field(0)] = semester_rs.field(1);
		semester_rs.next();
	}
	return semesters;
}
function getCurrentSemester() {
	var semester_rs = db.execute("SELECT id FROM Semester WHERE is_default='true'");
	if (semester_rs.isValidRow())
		return semester_rs.field(0); 
	return -1;
}

function getCurrentClasses() {
	var classes_rs = db.execute('SELECT id, name FROM Classes WHERE semester_id = (?) ORDER BY id', [getCurrentSemester()]);
	classes = new Array();
	while(classes_rs.isValidRow()) {
		classes[classes_rs.field(0)] = classes_rs.field(1);
		classes_rs.next();
	}
	return classes;
}

function populateClassDropDown() {
	//Clear the dropdown first
	while ($('classes').length > 0) $('classes').remove(0);
	
	//Then pull the class info and re-populate it.
	var classes = getCurrentClasses();
	for (i in classes) {
		o = document.createElement('option'); o.text = classes[i]; o.value = i;
		try { $('classes').add(o,null);} catch(ex) { $('classes').add(o); }
	}
}

function populateSemesterDropDown() {
	//Clear the dropdown first
	while ($('semesters').length > 0) $('semesters').remove(0);
	
	//Then pull the class info and re-populate it.
	var semesters = getAllSemesters();
	cur_semester = getCurrentSemester();
	for (i in semesters) {
		o = document.createElement('option'); o.text = semesters[i]; o.value = i;
		if (i == cur_semester) o.selected = 'selected';
		try { $('semesters').add(o,null);} catch(ex) { $('semesters').add(o); }
	}
}
function getClassColor(class_id) {
	var rs = db.execute("SELECT color FROM Classes WHERE id = '" + class_id + "'");
	var color;
	if (rs.isValidRow()){
		color = rs.field(0);
	}
	return color;
}

//Re-writes the contents of the assignments div. Big nasty function.
function refreshAssignments() {
	var rs = db.execute("SELECT Assignments.id, class_id, Assignments.name, complete, comments, date(datum), type, Classes.color FROM Assignments, Classes, Semester WHERE Classes.id = class_id AND Semester.id = semester_id AND is_default='true' ORDER BY datum, class_id");
	
	str = "<table border='1'><tr><th>Date</th>";
	classes = getCurrentClasses();
	for (i in classes) {
		color = getClassColor(i);
		str += "<th class='"+color+"'>" + classes[i] + "</th>";
	}
	str += "</tr>";
	
	var assignments = new Array();
	while (rs.isValidRow()) {		
		class_id = rs.field(1);
		assignment_name = rs.field(2);
		complete = rs.field(3);
		date_str = rs.field(5);
		assignment_type = rs.field(6);
		class_color = rs.field(7)
		
		if (assignments[date_str] == undefined) {
			assignments[date_str] = new Array();
		}
		if (assignments[date_str][class_id] == undefined) {
			assignments[date_str][class_id] = new Array();
		}
		assignments[date_str][class_id].push("<span class='" + assignment_type + " " + class_color + "'>" + assignment_name + "</span>");
		
		rs.next();
	}
	rs.close();
	
	for (each_date in assignments) {
		str += "<tr><td>" + each_date + "</td>";
		
		for (each_class in classes) {
			str += "<td>";
			if (assignments[each_date][each_class] != undefined) {
				for (each_assignment in assignments[each_date][each_class]) {
				//	alert(each_date + ", " + classes[each_class] + ", " + assignments[each_date][each_class][each_assignment]);
					str += assignments[each_date][each_class][each_assignment] + "<br />";
				}
			} else {
				str += "&nbsp;";
			}
			str += "</td>";
		}
		str += "</tr>";
	}
	
	str += "</table>";
	
	$('Assignments').innerHTML = str;
}

//Formats a date object and returns it as a string in the format sqlite likes.
Date.prototype.toSQLite = function() {
	datum = new Array(this.getFullYear(), this.getMonth() + 1, this.getDate(),
		this.getHours(), this.getMinutes(), this.getSeconds());
	
	for (i = 0; i <= 5; i++) {
		if (datum[i] < 10)
			datum[i] = "0" + datum[i];
	}
		
	date_str = datum[0] + "-" + datum[1] + "-" + datum[2];// + " " + datum[3] + ":" + datum[4] + ":" + datum[5]; 	
	return date_str;
}
//Sets the year, month, and date of a Date object all at once.
Date.prototype.setDatum = function(date_str) {
	datum = date_str.split('-');
	this.setFullYear(datum[0]);
	this.setMonth(datum[1] - 1);
	this.setDate(datum[2]);
	this.setHours(0);
	this.setMinutes(0);
	this.setSeconds(0);
	return this;
}


function $(id) {
	return document.getElementById(id);
}

function addAssignment() {
	db.execute('INSERT INTO Assignments (name, class_id, complete, type, datum) VALUES (?, ?, ?, ?, ?)', 
		[$('assignment_name').value, $('classes').value, "false", $('assignment_type').value, $('date').value]);
	$('assignment_name').value = "";
	refreshAssignments();
}
function addSemester() {
	db.execute("UPDATE Semester SET is_default='false'");
	db.execute("INSERT INTO Semester (name, is_default) VALUES ('"+$('semester_name').value+"', 'true')");
	$('semester_name').value = "";
	refreshSemester();
}
function switchSemesters() {
	db.execute("UPDATE Semester SET is_default='false'");
	db.execute("UPDATE Semester SET is_default='true' WHERE id = '" + $('semesters').value + "'");
	refreshSemester();
}

function markAssignmentDone(assignment_id) {
	db.execute("UPDATE Assignments SET complete='true' WHERE id = " + assignment_id);
	refreshAssignments();
}
function markAssignmentIncomplete(assignment_id) {
	db.execute("UPDATE Assignments SET complete='false' WHERE id = " + assignment_id);
	refreshAssignments();
}

function addClass() {
	db.execute('INSERT INTO Classes (name, semester_id, color) VALUES (?, ?, ?)', [$('class_name').value, getCurrentSemester(), $('class_color').value]);
	populateClassDropDown();
	refreshAssignments();
}

function refreshSemester() {
	populateSemesterDropDown();
	populateClassDropDown();
	refreshAssignments();
}	

</script>
<style type='text/css'>
.Homework {
}
.Reading {
	font-style:italic;
}
.Lab {
	text-decoration:underline;
}
.Project {
	font-weight:bold;
}
.Exam {
	text-decoration:underline;
	font-weight:bold;
}
.red {
	color:red;
}
.blue {
	color:blue;
}
</style>
</head>
<body onload="javascript:init();">
<h1>Assignment Tracker</h1>
<fieldset style='display:inline'>
	<legend>Add/Select Semester</legend>
	<table>
	<tr><td>Select:</td><td><select name='semesters' id='semesters' onchange='switchSemesters();'></select></td></tr>
	<tr><td>Or add new:</td><td><input name='semester_name' id='semester_name' /></td></tr>
	</table>
	<button onclick="javascript:addSemester();">Add Semester</button>
</fieldset>


<fieldset style='display:inline'>
	<legend>Add Classes</legend>
		<table>
		<tr><td>Class Name:</td><td><input id='class_name' name='class_name' /></td></tr>
		<tr><td>Class Color:</td><td><input id='class_color' name='class_color' /></td></tr>
		</table>
	<button onclick="javascript:addClass();">Add Class</button>
</fieldset>


<fieldset style='display:inline'>
	<legend>Add Assignments</legend>
	<table>
		<tr><td>Assignment Name:</td><td><input id="assignment_name" name="assignment_name" /></td></tr>
		<tr><td>Class: </td><td><select name='classes' id='classes'></select></td></tr>
		<tr><td>Type: </td><td>
			<select name='assignment_type' id='assignment_type'>
				<option value='Homework' class='Homework'>Homework</option>
				<option value='Reading' class='Reading'>Reading</option>
				<option value='Lab' class='Lab'>Lab</option>
				<option value='Project' class='Project'>Project</option>
				<option value='Exam' class='Exam'>Exam</option>
			</select></td></tr>
		<tr><td>Date: (YYYY-MM-DD)</td><td><input id='date' name='date' /></td></tr>
		<!--tr><td>Comments:</td><td><textarea id='comments' name='comments'></textarea></td></tr-->
	</table>
	<button onclick="javascript:addAssignment();">Add Assignment</button>
</fieldset>

<hr />
<div id='Assignments'></div>
</body>
</html>